/***
@param name  系统权限检测 
@return {status}  是否执行下一步
*/
const sysPermis = async (permissionID) => {
	// #ifdef APP-PLUS
	return new Promise((resolve, reject) => {
		plus.android.requestPermissions(
			[permissionID], // 理论上支持多个权限同时查询，但实际上本函数封装只处理了一个权限的情况。有需要的可自行扩展封装
			({ granted, deniedPresent, deniedAlways }) => {
				if (granted.length > 0) {
					// 已获取的权限
					resolve(true)
				}
				if (deniedPresent.length > 0) {
					// 拒绝本次申请的权限
					reject(false) 
				}
				if (deniedAlways.length > 0) {
					// 永久拒绝申请的权限  跳转页面权限页
					uni.navigateTo({
						url: '/pages/permision?permissionID=' + permissionID,
					})
					reject(false)
				}
			},
			(error) => {
				console.log('申请权限错误：' + error.code + " = " + error.message);
				reject(false)
			}
		);
	})
	// #endif
	// #ifdef H5
	return true
	// #endif
}

//打开相册
const chooseImage = async () => {
	const status = await sysPermis('android.permission.READ_EXTERNAL_STORAGE')
	if (!status) {
		return Promise.reject(false)
	}
	try {
		return new Promise((resolve, reject) => {
			uni.chooseImage({
				count: 1,
				sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
				sourceType: ['album'], //从相册选择
				success({ tempFilePaths, tempFiles }) {
					resolve({
						tempFilePaths,
						tempFiles
					})
					// tempFilePath可以作为img标签的src属性显示图片
				},
				fail(err) {
					console.log('err', err)
					resolve(false)
				},
				complete(e) {
					console.log(e)
				},
			})
		})
	} catch (e) {
		return false
		//TODO handle the exception
	}
}

//打开文件 chooseFile
const chooseFile = async ({ sourceType = ['album', 'camera'] } = {}) => {
	try {
		const res = await sysPermis('android.permission.READ_EXTERNAL_STORAGE');
		console.log('sysPermis[android.permission.READ_EXTERNAL_STORAGE]===>',res)
		return new Promise((resolve, reject) => {
			uni.chooseImage({
				count: 1,
				sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
				sourceType: ['album'], //从相册选择
				success({ tempFilePaths, tempFiles }) {
					resolve({ sucecess: true, tempFilePaths, tempFiles })
					// tempFilePath可以作为img标签的src属性显示图片
				},
				fail(err) {
					// sysPermis('android.permission.READ_EXTERNAL_STORAGE')
					console.log('err', err)
					reject(false)
				},
			})
		})
	} catch (e) {
		console.log(e)
		return Promise.reject(false)
		//TODO handle the exception
	}
}

export {
	chooseImage,
	chooseFile
}